package com.tianquan.miracle.beans;/**
 * @author starsea
 * @date 2024-09-28 下午10:24
 */

import com.tianquan.miracle.core.ClassLoad;
import com.tianquan.miracle.util.MiracleUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @BelongsProject: uploaddemo
 * @BelongsPackage: com.tianquan.miracle.beans
 * @Author: tianquan
 * @CreateTime: 2024-09-28  22:24
 * @Description: 扫描资源
 * @Version: 1.0
 */
public class ScannerClassLoad implements ClassLoad {

    public List<Class<?>> loadClass(String packageName) {

        List<Class<?>> classNames = new ArrayList<>();
        try {
            String packagePath = packageName.replace('.', '/');
            Enumeration<URL> resources = ClassLoader.getSystemClassLoader().getResources(packagePath);
            while (resources.hasMoreElements()) {
                URL resource = resources.nextElement();
                File directory = new File(resource.getFile());
                if (directory.exists()) {
                    findClassesInDirectory(directory, packageName, classNames);
                }
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return classNames;
    }

    private static void findClassesInDirectory(File directory, String packageName, List<Class<?>> classNames) throws ClassNotFoundException {
        File[] files = directory.listFiles();
        if (files == null) return;
        for (File file : files) {
            if (file.isDirectory()) {
                findClassesInDirectory(file, packageName + "." + file.getName(), classNames);
            } else if (file.getName().endsWith(".class")) {
                String className = packageName + "." + file.getName().substring(0, file.getName().length() - 6);
                classNames.add(MiracleUtils.getClassLoader().loadClass(className));
            }
        }
    }

}



